package com.example.helloworld;

import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import cfg.Flickr;

import com.gmail.yuyang226.flickr.oauth.OAuth;
import com.gmail.yuyang226.flickr.oauth.OAuthToken;
import com.gmail.yuyang226.flickr.people.User;
import com.gmail.yuyang226.flickrj.sample.android.tasks.GetOAuthTokenTask;
import com.gmail.yuyang226.flickrj.sample.android.tasks.OAuthTask;

public class FlickConnectActivity extends Activity {

	public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";

	public static final String CALLBACK_SCHEME = "flickr-oauth"; //$NON-NLS-1$
	public static final String PREFS_NAME = "vincentmouge pref"; //$NON-NLS-1$
	public static final String KEY_OAUTH_TOKEN = "ae4d400693efafc9ec5e4216cdb9d0da"; //$NON-NLS-1$
	public static final String KEY_TOKEN_SECRET = "f988234812571ed7"; //$NON-NLS-1$
	public static final String KEY_USER_NAME = "vincentmouge"; //$NON-NLS-1$
	public static final String KEY_USER_ID = "66277186@N07"; //$NON-NLS-1$

	String from;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_flick_connect);

		Bundle extras = getIntent().getExtras();
		from = extras.getString("from");

		// autoconnect
		flickrConnect();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_flick_connect, menu);
		return true;
	}

	/** Called when the user clicks the Home button */
	public void homeClickHandler(View v) {
		Intent intent = new Intent(this, HomeActivity.class);
		startActivity(intent);
	}

	/** Called when the user clicks the Send button */
	public void sendList(View view) {
		Intent intent = new Intent(this, ListActivity.class);
		startActivity(intent);
	}

	private void flickrConnect() {
		// String apiKey = cfg.Flickr.API_KEY;
		// Flickr f = new Flickr(apiKey);
		// TestInterface testInterface = f.getTestInterface();
		// Collection results = testInterface.echo(Collections.EMPTY_LIST);

		OAuth oauth = getOAuthToken();

		if (oauth == null || oauth.getUser() == null) {
			if (from != null && from.equals("MainActivity")) {
				OAuthTask task = new OAuthTask(this);
				task.execute();
			}
		} else {
			load(oauth);
		}
	}

	// OAUTH
	// OAUTH
	// OAUTH
	// OAUTH
	// OAUTH

	private void load(OAuth oauth) {
		if (oauth != null) {
			Flickr.OAUTH_SESSION = oauth;

			Intent intent = new Intent(this, HomeActivity.class);
			startActivity(intent);
		}else{
			Log.e("PANIC ", "Flickr.OAUTH_SESSION");
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		Intent intent = getIntent();
		String scheme = intent.getScheme();
		OAuth savedToken = getOAuthToken();
		if (CALLBACK_SCHEME.equals(scheme)
				&& (savedToken == null || savedToken.getUser() == null)) {
			Uri uri = intent.getData();
			String query = uri.getQuery();
			Log.d("Returned Query: {}", query); //$NON-NLS-1$
			String[] data = query.split("&"); //$NON-NLS-1$
			if (data != null && data.length == 2) {
				String oauthToken = data[0].substring(data[0].indexOf("=") + 1); //$NON-NLS-1$
				String oauthVerifier = data[1]
						.substring(data[1].indexOf("=") + 1); //$NON-NLS-1$
				Log.d("OAuth Token: {}; OAuth Verifier: {}", oauthToken + " & " + oauthVerifier); //$NON-NLS-1$

				OAuth oauth = getOAuthToken();
				if (oauth != null && oauth.getToken() != null
						&& oauth.getToken().getOauthTokenSecret() != null) {
					GetOAuthTokenTask task = new GetOAuthTokenTask(this);
					task.execute(oauthToken, oauth.getToken()
							.getOauthTokenSecret(), oauthVerifier);
				}
			}
		}

	}

	public void onOAuthDone(OAuth result) {
		if (result == null) {
			Toast.makeText(this, "Authorization failed", //$NON-NLS-1$
					Toast.LENGTH_LONG).show();
		} else {
			User user = result.getUser();
			OAuthToken token = result.getToken();
			if (user == null || user.getId() == null || token == null
					|| token.getOauthToken() == null
					|| token.getOauthTokenSecret() == null) {
				Toast.makeText(this, "Authorization failed", //$NON-NLS-1$
						Toast.LENGTH_LONG).show();
				return;
			}
			String message = String
					.format(Locale.US,
							"Authorization Succeed: user=%s, userId=%s, oauthToken=%s, tokenSecret=%s", //$NON-NLS-1$
							user.getUsername(), user.getId(),
							token.getOauthToken(), token.getOauthTokenSecret());
			Toast.makeText(this, message, Toast.LENGTH_LONG).show();
			saveOAuthToken(user.getUsername(), user.getId(),
					token.getOauthToken(), token.getOauthTokenSecret());

			load(result);
		}
	}

	public OAuth getOAuthToken() {
		// Restore preferences
		SharedPreferences settings = getSharedPreferences(PREFS_NAME,
				Context.MODE_PRIVATE);
		String oauthTokenString = settings.getString(KEY_OAUTH_TOKEN, null);
		String tokenSecret = settings.getString(KEY_TOKEN_SECRET, null);
		if (oauthTokenString == null && tokenSecret == null) {
			Log.w("WARNING", "No oauth token retrieved"); //$NON-NLS-1$
			return null;
		}
		OAuth oauth = new OAuth();
		String userName = settings.getString(KEY_USER_NAME, null);
		String userId = settings.getString(KEY_USER_ID, null);
		if (userId != null) {
			User user = new User();
			user.setUsername(userName);
			user.setId(userId);
			oauth.setUser(user);
		}
		OAuthToken oauthToken = new OAuthToken();
		oauth.setToken(oauthToken);
		oauthToken.setOauthToken(oauthTokenString);
		oauthToken.setOauthTokenSecret(tokenSecret);
		Log.d("Retrieved token from preference store: oauth token={}, and token secret={}", oauthTokenString + " & " + tokenSecret); //$NON-NLS-1$
		return oauth;
	}

	public void saveOAuthToken(String userName, String userId, String token,
			String tokenSecret) {
		Log.d("Saving userName=%s, userId=%s, oauth token={}, and token secret={}", userName + " & " + userId + " & " + token + " & " + tokenSecret); //$NON-NLS-1$
		SharedPreferences sp = getSharedPreferences(PREFS_NAME,
				Context.MODE_PRIVATE);
		Editor editor = sp.edit();
		editor.putString(KEY_OAUTH_TOKEN, token);
		editor.putString(KEY_TOKEN_SECRET, tokenSecret);
		editor.putString(KEY_USER_NAME, userName);
		editor.putString(KEY_USER_ID, userId);
		editor.commit();
	}

	// DEPENDING ACTIVITY
	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onNewIntent(android.content.Intent)
	 */
	@Override
	protected void onNewIntent(Intent intent) {
		Log.i("-------- onNewIntent! ----------", intent.toString());
		// this is very important, otherwise you would get a null Scheme in the
		// onResume later on.
		setIntent(intent);
	}

}
